package com.huluobo.kotlinim1907a.contract.contact

import android.util.Log
import com.huluobo.kotlinim1907a.data.ContactListItem
import com.huluobo.kotlinim1907a.db.Contact
import com.huluobo.kotlinim1907a.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2022/1/14.
 */
class ContactPresenter(val view: ContactContract.View) : ContactContract.Presenter {
    val contactListItems = mutableListOf<ContactListItem>()
    override fun loadContacts() {
        doAsync {
            try {
                contactListItems.clear()
                IMDatabase.instance.deleteAllContacts()
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer

                //按照首字符进行排序
                userNames.sortBy { it[0] }
//                userNames.forEach {
//                    //拿到每一个联系人的对象(名字,首字符,是否显示首字符)
//                    //it代表userNames中每个String,toUpperCase(已过时可以使用uppercaseChar替换)代表转换为大写字母
//                    val contactListItem = ContactListItem(it, it[0].uppercaseChar())
//                    contactListItems.add(contactListItem)
//                }
                userNames.forEachIndexed { index, it ->
                    //什么时候显示首字符,index=0
                    //username上一位的首字符如果与当前首字符不同
                    val showFirstLetter = index == 0 || it[0] != userNames[index - 1][0]
                    val contactListItem =
                        ContactListItem(it, it[0].uppercaseChar(), showFirstLetter)
                    contactListItems.add(contactListItem)
                    val contact = Contact(mutableMapOf("name" to it))
                    IMDatabase.instance.saveContact(contact)
                }
                runOnUIThread { view.onLoadContactsSuccess() }
            } catch (e: HyphenateException) {
                Log.i("TagA", "e:${e.message}")
                runOnUIThread { view.onLoadContactsFailed() }
            }
        }
    }
}